package com.zivwu.utils.device;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import androidx.annotation.Nullable;

import com.zivwu.utils.model.Photo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MediaStoreHelper {
    private static final String ALL_BUCKET_DISPLAY_NAME = "所有图片";
    private Context context;

    public MediaStoreHelper(Context context) {
        this.context = context;
    }

    public ArrayList<Map.Entry<String, List<Photo>>> getPhotos(@Nullable String sortOrder) {
        return selectPhotos(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, sortOrder);
    }

    public ArrayList<Map.Entry<String, List<Photo>>> getPhotosByModifiedDesc() {
        return getPhotos(MediaStore.Images.ImageColumns.DATE_MODIFIED + " desc");
    }



    private ArrayList<Map.Entry<String, List<Photo>>> sortAllPhoto(Map<String, List<Photo>> map) {
        List<Photo> totle = new ArrayList<>();
        Iterator<Map.Entry<String, List<Photo>>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, List<Photo>> next = iterator.next();
            List<Photo> photos = next.getValue();
            Collections.sort(photos, Collections.<Photo>reverseOrder());
            totle.addAll(photos);
        }
        Collections.sort(totle, Collections.<Photo>reverseOrder());
        map.put("所有图片", totle);
        ArrayList<Map.Entry<String, List<Photo>>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<String, List<Photo>>>() {
            @Override
            public int compare(Map.Entry<String, List<Photo>> o1, Map.Entry<String, List<Photo>> o2) {
                if (o1.getValue().size() == o2.getValue().size())
                    return 0;
                return o1.getValue().size() > o2.getValue().size() ? -1 : 1;
            }
        });
        return entries;
    }

    private ArrayList<Map.Entry<String, List<Photo>>> sortByCount(Map<String, List<Photo>> map) {
        ArrayList<Map.Entry<String, List<Photo>>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<String, List<Photo>>>() {
            @Override
            public int compare(Map.Entry<String, List<Photo>> o1, Map.Entry<String, List<Photo>> o2) {
                if (o1.getValue().size() == o2.getValue().size())
                    return 0;
                return o1.getValue().size() > o2.getValue().size() ? -1 : 1;
            }
        });
        return entries;
    }


    public ArrayList<Map.Entry<String, List<Photo>>> selectPhotos(Uri uri, @Nullable String selection,
                                                 @Nullable String[] selectionArgs,
                                                 @Nullable String sortOrder) {
        String[] projection = getProjection();
        Map<String, List<Photo>> map = new HashMap<>();
        Cursor cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
        if (cursor == null || cursor.getCount() <= 0)
            return new ArrayList<>();

        List<Photo> allPhotos = null;
        cursor.moveToFirst();
        do {
            //getPhotos data form cursor
            String bucket_display_name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME));
            int _id = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.ImageColumns._ID));
            String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA));
            String display_name = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
            String mime_type = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.MIME_TYPE));
            int date_modified = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATE_MODIFIED));
            Photo photo = new Photo(bucket_display_name, _id, path, display_name, mime_type, date_modified);

            if (allPhotos == null) {
                allPhotos = new ArrayList<>();
                map.put(ALL_BUCKET_DISPLAY_NAME, allPhotos);
            }
            allPhotos.add(photo);
            //check map has bucket_display_name
            List<Photo> items = map.get(bucket_display_name);
            if (items == null) {
                items = new ArrayList<>();
                map.put(bucket_display_name, items);
            }
            items.add(photo);

        } while (cursor.moveToNext());
        cursor.close();
        return sortByCount(map);
    }


    /**
     * 获取需要获得的 Column(列)
     *
     * @return
     */
    private String[] getProjection() {
        String[] projection = {
                MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
                MediaStore.Images.ImageColumns.DATE_MODIFIED,
                MediaStore.Images.ImageColumns.DISPLAY_NAME,
                MediaStore.Images.ImageColumns.DATA,
                MediaStore.Images.ImageColumns.MIME_TYPE,
                MediaStore.Images.ImageColumns._ID};
        return projection;
    }
}